/**
 *
 * @date    2016-06-02 09:59:21
 * @author  hch wy
 */

$(function(){
        var $popReg = $('#popReg'),
            $popLogin = $('#popLogin'),
            $userClass = $('#userClass'),
            $regBox = $('#regBox'),
            getKind = 6,
            regTitle = '新用户注册';
        /*注册类型*/
        $('body').on('click', '#userClass li, #indexUserClass a, .triggerDesignerReg, .triggerMsReg, .triggerDrReg', function(){
            getKind = parseInt($(this).data('mod'));
            switch (getKind)
            {
                case 1:
                    regTitle = '设计师注册';
                    break;
                case 2:
                    regTitle = '品牌商注册';
                    break;
                case 3:
                    regTitle = '买手注册';
                    break;
                case 4:
                    regTitle = '达人注册';
                    break;
                case 5:
                    regTitle = '供应链注册';
                    break;
                case 6:
                    regTitle = '新用户注册';
                    break;
            }
            $('#registerForm #regTitle').text(regTitle);
            $(this).parents('#userClass').fadeOut();
            $regBox.css({visibility: 'visible'});
            $popReg.fadeIn();
            $.ajax({
                type: 'GET',
                url: getRegisterAdvertisementApi,
                dataType: 'json',
                data: {'kind': getKind},
                success : function(result){
                    //var imgUrl = result.data[0];
                    var imgUrl = result.data[0].advertiseChimgUrl || '';
                    console.log(result.data);
                    $('.notesPic img').attr('src', imgUrl).css({visibility: 'visible'});
                },
                error : function(){
                    layer.msg('网络错误，请重试！', {time: 1500});
                }
            });
        });
        /*  @弹窗
            @triggersEle：触发弹层的节点
            @popDom：弹层的父节点
            @ajaxUrl：对应弹层的广告api
            @defaultImg：默认的广告图
        */
        var openPop = function(triggersEle, popDom, ajaxUrl, ajaxParameter){
            $(triggersEle).on('click', function(){
                $.ajax({
                    type: 'GET',
                    url: ajaxUrl,
                    dataType: 'json',
                    data: {'page': ajaxParameter},
                    success : function(result){
                        //var imgUrl = result.data[0];
                        var imgUrl = result.data[0].advertiseChimgUrl || '';
                        console.log(result);
                        $('.notesPic img').attr('src', imgUrl).css({visibility: 'visible'});
                    },
                    error : function(){
                        layer.msg('网络错误，请重试！', {time: 1500});
                    }
                });
                popDom.fadeIn();
            });
        }
        /*头部注册按钮弹窗*/
        $('#regBtn').on('click', function(){
            $userClass.fadeIn();
            $popReg.fadeIn();
        });

        /*头部登录按钮弹窗*/
        // openPop('#loginBtn', $popLogin, getAdvertisementApi, 'login');

        /*弹窗立即登录*/
        //$popReg.on('click', '#popLoginBtn', function(){
         //   $(this).parents('.pop-box').hide();/*先隐藏父窗口*/
       // });
       // openPop('#popLoginBtn', $popLogin, getAdvertisementApi, 'login');/*再执行登录弹层*/

        /*弹窗立即注册*/
        $popLogin.on('click', '#popRegBtn', function(){
            $(this).parents('.pop-box').hide();
            $userClass.fadeIn();
            $popReg.fadeIn();
        });

        /*关闭弹窗*/
        $('body').on('click', '.lyclose.pop-close', function(){
            $(this).parents('.pop-box').hide();
            $userClass.hide();
            $regBox.css({visibility: 'hidden'});
            //$('.notesPic img').attr('src', STATIC_PATH + 'img/dot.png').css({visibility: 'hidden'});
        });


        $('#loginFormBtn').on('click', function(){
            //console.log('loginFormBtn');return false;
            var loginPhone = $('#loginPhone').val(),
                password = $('#password').val(),
                cation = 1;
            var regexemail = /^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$/ig,
                regexphone = /^(13[0-9]|14[0-9]|15[0-9]|17[0-9]|18[0-9])\d{8}$/;
            var ispass = false,
                source = 1,
                isemailpass = false,
                isphonepass = false;
            /*验证邮件*/
            if (regexemail.test(loginPhone)) {
                isemailpass = true;
                source = 5;
            }
            /*验证手机*/
            if (regexphone.test(loginPhone)) {
                isphonepass = true;
                source = 1;
            }

            if (isphonepass || isemailpass) {
                ispass = true;
            }else{
                layer.msg('请输入正确的手机号码或邮箱');
                return false;
            }


            var postData = {
                phone: loginPhone,
                password: password,
                cation: 1,
                source:source
            };

            $.ajax({
                type: 'POST',
                url: materialLoginApi,
                data: postData,
                dataType:"json",
                success: function(result){
                    //console.log(result);
                //layer.msg(result.text);

                var _data = result || {},
                    _code = parseInt(_data.state,10);
                    if(_code === 1){
                        setTimeout(function(){
                            window.location.reload();
                        },1000)
                        
                    }else if(_code === -1){
                        layer.msg(_data.text, {time: 1500});
                    }else if(_code === 2){
                        layer.msg(_data.text);
                        setTimeout(function(){
                            window.location.href=_data.url;
                        },1000)
                    }else{
                        layer.msg(_data.desc, {time: 1500});
                    }
                },
                error: function(){
                    layer.msg('网络错误，请重试！', {time: 1500});
                }
            });
        })



        /*登录 注册切换*/
        var regLock=false;
        $span =$('.tabLogin').find('span');
        $span.on('click',function(){
            var index=$(this).index();
            $(this).addClass('active').siblings('span').removeClass('active');
            $('.js-login').hide().eq(index).show();
        });
        /*手机号唯一*/
        $('body').on('blur', '#registerForm #phone', function(){
            var phone = $.trim($(this).val());/*忽略空格wy*/
            if(phone){
                $.ajax({
                    type: 'POST',
                    url: checkUsernameUrl,
                    data: {
                        'username': phone
                    },
                    success: function(result){
                    var _data = JSON.parse(result) || {},
                        _code = parseInt(_data.code,10);
                        if(_code === 1000){
                            regLock=true;
                            return true;
                        }else{
                            layer.msg(_data.desc, {time: 1500});
                            $('#phone').focus();
                        }
                    },
                    error: function(){
                        layer.msg('网络错误，请重试！', {time: 1500});
                    }
                });
            }
        });
        /*昵称唯一wy*/
        $('#nickname').on('blur', function(){
            var nickname = $.trim($(this).val());
            if(nickname){
                $.ajax({
                    type: 'POST',
                    url: checknicknameUrl,
                    data: {
                        'nickname': nickname
                    },
                    success: function(result){
                    var _data = JSON.parse(result) || {},
                        _code = parseInt(_data.code,10);
                        if(_code === 1000){/*昵称ok*/
                            return true;
                        }else{/*昵称已占用*/
                            layer.msg(_data.desc, {time: 1500});
                            $('#nickname').focus();
                        }
                    },
                    error: function(){
                        layer.msg('网络错误，请重试！', {time: 1500});
                    }
                });
            }
        });
        /*登录*/
        $("#loginForm").validate({
            rules: {
                phone: {
                    //phone: "loginPhone",
                    required: true
                },
                password:{
                    //password1:"password1",
                    required: true
                }
            },
            messages: {
                phone: {
                    required: "手机号码不能为空"
                },
                password: {
                    required: "密码不能为空"
                }
            },
            onkeyup:false,
            focusCleanup:true,
            errorClass:"errorInfo",
            submitHandler: function(form) {

                 loginSubmit()
            }
        });
        // 登录成功
        function loginSubmit(){            
            var phone = $('#loginPhone').val();
            var password = $('#password').val();
            var loginData = {'username' : phone, 'password' : password};
            if(localStorage["errorCount"]){
                errorCount=Number(localStorage["errorCount"])
            }
            if(errorCount==0){
                localStorage["errorTime"]=new Date().getTime()
            }
            if(errorCount>=3){
                var lastTime=Number(localStorage["errorTime"])
                var currentTime=new Date().getTime()
                if(currentTime-lastTime<=60*1000*10){
                    $('#loginCaptchaimg').show()

                    var smsLoginCaptchaimg = $("#loginCaptcha").val();
                    if(!smsLoginCaptchaimg){
                        layer.msg('请填写验证码');
                    }
                    loginData['captchaimg'] = smsLoginCaptchaimg;

                }else{
                    errorCount=0
                    localStorage["errorCount"]=0
                    localStorage["errorTime"]=new Date().getTime()
                }
            }
            $.ajax({
                 type : 'POST',
                 url  :  loginUrl,
                 dataType : 'json',
                 data : loginData,
                 beforeSend : function(){},
                 success : function(returnMsg){
                    if(!returnMsg.success){
                        errorCount++
                        localStorage["errorCount"]=errorCount;
                        layer.msg(returnMsg.message);
                    }else{
                        errorCount=0
                        localStorage["errorCount"]=0
                        window.location.reload();
                        //parent.location.reload();
                        //console.log(loginfromUrl);
                        //window.location.href = loginfromUrl;
                    }
                 },
                 error : function(){
                     layer.msg('登录失败');
                 }
            });
         }
        /*短信登录*/
        $('#SMSlogin').validate({
            rules: {
                phone1: {
                    phone: "phone",
                    required: true
                },
                captcha:{
                    required: true
                },
                phonecaptcha1:{
                    required: true
                }
            },
            messages: {
                phone1: {
                    required: "手机号码不能为空"
                },
                captcha:{
                    required:"请输入正确的验证码"
                },
                phonecaptcha1:{
                    required:"请输入正确的短信验证码"
                }
            },
            onkeyup:false,
            focusCleanup:true,
            errorClass:"errorInfo",
            submitHandler: function(form) {
                 smsLoginSubmit()
            }
        });
        /*短信登录成功*/
        function smsLoginSubmit(){
             var username = $('#phone1').val();
             var captchaimg = $('#captcha').val();
             var phonecaptcha1 = $('#phonecaptcha1').val();
             var loginData = {'username' : username, 'captchaimg' : captchaimg, 'smsCode' : phonecaptcha1};
             $.ajax({
                 type : 'POST',
                 url  :  smsUrl,
                 dataType : 'json',
                 data : loginData,
                 beforeSend : function(){},
                 success : function(returnMsg){
                     if(!returnMsg.success){
                        layer.msg(returnMsg.message);
                     }else{
                        window.location.reload();
                    }
                 },
                 error : function(){
                     layer.msg('登录失败');
                 }
             });
         }
         /*发送短信验证码*/
        //  var sendSmsCodeLockPhone=true;/*注册*/
        //  var sendSmsCodeLockPhone1=true;/*短信登录*/
        //  function sendSmsCode(phoneID, smsCodeType){
        //         /*$('#phone').trigger('blur')*/
        //         var sendSmsCodeLock = 'sendSmsCodeLock'+phoneID;
        //         if(/^(13[0-9]|14[0-9]|15[0-9]|17[0-9]|18[0-9])\d{8}$/.test($("#"+phoneID).val())){
        //             if(phoneID=="phone"||phone=="forgetPhone"){
        //                 /*只有等ajax手机号码返回结果,手机号码不存在时才能注册*/
        //                 if(!regLock)return
        //             }
        //             if(!sendSmsCodeLock)return
        //              sendSmsCodeLock=false
        //              var phone = $("#"+phoneID).val();/*登录和注册*/
        //              var smsCodeData = {'username' : phone, 'type': smsCodeType};//smsCodeType 不为空，则不验证手机号是否存在
        //              if(phoneID=="phone"){smsCodeData["type"]=1}
        //              if(window.localStorage&&localStorage[phoneID]){
        //                 var lastTime=Number(localStorage[phoneID]);
        //                 var currTime=new Date().getTime();
        //                 if(currTime-lastTime<=60*1000){
        //                     /*1分钟之内只能发送1次*/
        //                     layer.msg('操作过于频繁');
        //                     sendSmsCodeLock=true
        //                      return
        //                 }else{
        //                      localStorage.phoneID=new Date().getTime();
        //                 }
        //              }
        //             $.ajax({
        //                  type : 'POST',
        //                  url  : sendSmsCodeUrl,
        //                  dataType : 'json',
        //                  data : smsCodeData,
        //                  beforeSend : function(){},
        //                  success : function(returnMsg){
        //                      console.log(returnMsg);
        //                      if(!returnMsg.success){
        //                         sendSmsCodeLock=true;
        //                         layer.msg(returnMsg.message);
        //                         $('.retransmission').html("点击获取验证码").removeAttr("style")
        //                      }else{
        //                         var sec=60;
        //                         if(window.localStorage){
        //                             localStorage[phoneID]=new Date().getTime();
        //                         }
        //                         $('.' + phoneID).css("background","none")
        //                         var tirm=setInterval(function(){
        //                             sec--
        //                             $('.' + phoneID).html("重新发送("+sec+")")
        //                             if(sec<=0){
        //                                 clearInterval(tirm)
        //                                 $('.' + phoneID).html("点击获取验证码")
        //                                 sendSmsCodeLock=true;
        //                                 $('.' + phoneID).removeAttr("style")
        //                             }
        //                         }, 1000)
        //                      }
        //                  },
        //                  error : function(){
        //                      layer.msg('发送短信验证码失败');
        //                      $('.retransmission').html("点击获取验证码").removeAttr("style")
        //                  }
        //              });
        //         }else{
        //             layer.msg('请输入正确的手机号码');
        //         }
        //  }
        // window.sendSmsCode=sendSmsCode;
        function wbLogin(){
            WB2.login(function(data) {
                WB2.anyWhere(function(W){
                    W.parseCMD('/account/get_uid.json', function(oResult, bStatus){
                        if(bStatus){
                            var uid=oResult.uid
                            /*此uid是唯一id，下次登录通过此id来判断是否已经登陆过了  1997429417*/
                            $.ajax({
                                type: 'GET',
                                url: checkBindApiUrl ,
                                data:{source:4,uid:uid},
                            })
                            .done(function(data){
                                data=JSON.parse(data)
                                console.log(data)
                                if(data.success){//如果已经绑定
                                    //window.location.href = loginfromUrl;
                                    window.location.reload();
                                }else{
                                    /*如果还未绑定调到绑定页面*/
                                    window.location.href="/member/bind-phone.html?wb="+uid;
                                }
                            })
                            .fail(function(){
                                layer.msg("网络发送错误，请稍后再试")
                            })
                        }
                    }, {source: 3992758230}, {
                        method : 'get',
                        cache_time : 30
                    });
                });
            });
        }

        $('#xinlang').on('click',function(){
            if(WB2.checkLogin()){
                /*如果已经登录就先退出登录再重新登录，不然不会弹出授权框*/
                WB2.logout(function(){
                    wbLogin();
                })
            }else{
                wbLogin();
            }
        });
        /*QQ登录*/
         $('#qq').on('click',function(){
            QC.Login.showPopup({
               appId:"101335460",
               redirectURI:"http://www.wttai.com/member/bind-transition.html?111"
            });
         });

        /*通过url参数，开启第三方登录入口 login=open*/
        /*function _getQueryString(name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            if (r !== null) return decodeURIComponent(r[2]);
            return null;
        }
        var loginOpen = _getQueryString('login');
        console.log(loginOpen);
        if(loginOpen !== 'open'){
            // 如果url参数不正确，解除事件
            $('#xinlang').off();
            $('#weixin a').removeAttr("href");
        }*/

})
